package com.example.service;

import com.example.entity.User;
import com.example.repository.BsUserRepository;
import com.example.repository.UserRepository;
import com.example.util.BaseRepository;
import com.example.util.QueryParams;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserService extends BaseRepository {

    @Autowired
    private BsUserRepository bsUserRepository;
    @Autowired
    private UserRepository userRepository;
    @PersistenceContext
    private EntityManager entityManager;

    public Map<String, Object> getUserList(QueryParams queryParams, Pageable pageable) {
        Map<String, Object> map = new HashMap<>();
       /* Page<BsUser> page = bsUserRepository.findAll(new Specification<BsUser>() {
            @Override
            public Predicate toPredicate(Root<BsUser> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                Predicate querySQL = null;
                if(null != id){
                    querySQL = criteriaBuilder.and(criteriaBuilder.equal(root.join("store_id",JoinType.INNER).get("id"),id));
                }
                if(null != querySQL){
                    criteriaQuery.where(querySQL);
                }
                return querySQL;
            }
        },pageable);*/
        StringBuilder sql = new StringBuilder("select t1.`id`,t1.`user_name`,t1.`nick_name`,date_format(t1.register_time, '%Y-%m-%d %H:%i:%s') as register_time,t2.`partner_name` from bs_user t1,bs_partner t2 where t1.`store_id` =t2.`id`");
        List values = analysisQueryParams(sql, queryParams);
        Query queryData = entityManager.createNativeQuery(sql.toString());
        for (int i = 0; i < values.size(); i++) {
            queryData.setParameter(i + 1, values.get(i));
        }
        map.put("total", queryData.getResultList().size());
        //设置分页参数
        queryData.setFirstResult(pageable.getOffset());
        queryData.setMaxResults(pageable.getPageSize());
        //转换为Map集合
        queryData.unwrap(org.hibernate.SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        map.put("data", queryData.getResultList());
        return map;
    }

    public User findByuserName(String userName) {
        return userRepository.findBypartnerName(userName);
    }

    public User editPassword(User user) {
        user = userRepository.saveAndFlush(user);
        return user;
    }
}
